using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPFTemplateLib.WpfHelpers
{
	public static class UiHelper
	{
		/// <summary>
		/// 获取指定 <see cref="UIElement"/> 对象的 RenderTransform，没有时给它创建一个并赋值
		/// </summary>
		/// <typeparam name="T">Transform 子类型</typeparam>
		/// <param name="uiTarget">UI 对象</param>
		/// <returns>对象的 RenderTransform</returns>
		public static T EnsureRenderTransform<T>(UIElement uiTarget)
			where T : Transform
		{
			if (uiTarget.RenderTransform is T)
				return uiTarget.RenderTransform as T;
			else
			{
				T instance = typeof(T).Assembly.CreateInstance(typeof(T).FullName) as T;
				uiTarget.RenderTransform = instance;
				return instance;
			}
		}

		/// <summary>
		/// 在 UIElementCollection 中查找所有满足条件的子元素
		/// </summary>
		/// <typeparam name="T">要查找的元素类型</typeparam>
		/// <param name="collection">UIElementCollection</param>
		/// <param name="predicate">条件表达式</param>
		/// <returns>所有满足条件的子元素</returns>
		public static IEnumerable<T> FindChildren<T>(this UIElementCollection collection, Func<T, bool> predicate = null)
			where T : UIElement
		{
			foreach (var element in collection)
			{
				if (element is T t && (predicate == null || predicate(t)))
					yield return t;
			}
		}
		/// <summary>
		/// 判断 UIElementCollection 中是否存在满足条件的子元素
		/// </summary>
		/// <typeparam name="T">要查找的元素类型</typeparam>
		/// <param name="collection">UIElementCollection</param>
		/// <param name="predicate">条件表达式</param>
		/// <returns>是否存在满足条件的子元素</returns>
		public static bool IsExistsChild<T>(this UIElementCollection collection, Func<T, bool> predicate = null)
			where T : UIElement
		{
			//此处使用 foreach 循环而不是 LINQ 的 Any() 方法，据说是性能更好;
			foreach(var _ in collection.FindChildren<T>(predicate))
			{
				return true;
			}

			return false;
		}
	}
}
